What is safe-json-parse?
The safe-json-parse npm package provides a safer way to parse JSON strings, handling errors gracefully and avoiding potential crashes due to malformed JSON.
What are safe-json-parse's main functionalities?
Safe Parsing with Default Value
This feature allows you to parse a JSON string safely. If the JSON is malformed, it returns a default value instead of throwing an error.
const safeJsonParse = require('safe-json-parse');
const jsonString = '{"key": "value"}';
const [err, result] = safeJsonParse(jsonString, { defaultValue: {} });
console.log(err); // null
console.log(result); // { key: 'value' }
Error Handling
This feature provides error handling by returning an error object if the JSON string is malformed, allowing you to handle the error gracefully.
const safeJsonParse = require('safe-json-parse');
const malformedJsonString = '{key: value}';
const [err, result] = safeJsonParse(malformedJsonString);
console.log(err); // Error: Unexpected token k in JSON at position 1
console.log(result); // undefined
Other packages similar to safe-json-parse
json-parse-safe
The json-parse-safe package provides a similar functionality by safely parsing JSON strings and returning a default value or an error object if the JSON is malformed. It is comparable to safe-json-parse in terms of error handling and default value support.
json5
The json5 package allows for more lenient JSON parsing, supporting a superset of JSON that includes additional features like comments and trailing commas. While it provides safe parsing, it is more feature-rich compared to safe-json-parse.
fast-json-parse
The fast-json-parse package focuses on performance and provides a fast way to parse JSON strings safely. It includes error handling similar to safe-json-parse but is optimized for speed.
safe-json-parse
Parse JSON safely without throwing
Example (callback)
var safeParse = require("safe-json-parse/callback")
safeParse("{}", function (err, json) {
})
safeparse("WRONG", function (err) {
})
Example (tuple)
var safeParse = require("safe-json-parse/tuple")
var tuple1 = safeParse("{}")
var json = tuple1[1]
var tuple2 = safeparse("WRONG")
var err = tuple2[0]
var tuple3 = safeParse(something)
if (tuple3[0]) {
var err = tuple3[0]
} else {
var json = tuple3[1]
}
Example (result)
var Result = require('rust-result')
var safeParse = require('safe-json-parse/result')
var result1 = safeParse("{}")
var json = Result.Ok(result1)
var result2 = safeparse("WRONG")
var err = Result.Err(result2)
var result3 = safeParse(something)
if (Result.ifErr(result3)) {
var err = Result.Err(result3)
} else if (Result.ifOk(result3)) {
var json = Result.Ok(result3)
}
Installation
npm install safe-json-parse
Contributors
MIT Licenced